/**
 * Dashboard API服务
 * 提供数据看板相关的API接口调用
 */

import Maxios from '@/Http/MesHelp'

// API基础路径
const API_BASE_URL = '/api/Dashboard'

// 数据看板统计数据类型定义
export interface DashboardStats {
  totalOrders: number
  productionCompletionRate: number
  equipmentRunningRate: number
  totalMaterialStock: number
  orderTrend: number
  productionTrend: number
  equipmentTrend: number
  materialTrend: number
}

// 订单状态分布数据类型定义
export interface OrderStatusDistribution {
  timeRange: string
  inProgress: number
  completed: number
  pending: number
  paused: number
}

// 车间产线状态数据类型定义
export interface WorkshopStatus {
  id: number
  name: string
  status: string
  statusClass: string
  progress: number
  lines: Array<{
    id: number
    name: string
    status: string
  }>
}

// 物料库存预警数据类型定义
export interface MaterialAlert {
  id: number
  materialName: string
  currentQty: number
  warnQty: number
  level: string
  icon: string
  time: string
}

// OEE设备效率数据类型定义
export interface OEEData {
  oee: number
  availability: number
  performance: number
  quality: number
}

// 实时事件数据类型定义
export interface RealtimeEvent {
  id: number
  time: string
  content: string
  source: string
  type: string
}

// 生产进度数据类型定义
export interface ProductionProgress {
  orderName: string
  plannedProgress: number
  actualProgress: number
}

class DashboardService {
  /**
   * 获取数据看板统计数据
   * @returns Promise<DashboardStats>
   */
  static async getDashboardStats(): Promise<DashboardStats> {
    try {
      const response = await Maxios.get(`${API_BASE_URL}/GetDashboardStats`)
      
      if (response.data.code === 200) {
        const data = response.data.data
        return {
          totalOrders: data.totalOrders || 0,
          productionCompletionRate: data.productionCompletionRate || 0,
          equipmentRunningRate: data.equipmentRunningRate || 0,
          totalMaterialStock: data.totalMaterialStock || 0,
          orderTrend: data.orderTrend || 0,
          productionTrend: data.productionTrend || 0,
          equipmentTrend: data.equipmentTrend || 0,
          materialTrend: data.materialTrend || 0
        }
      } else {
        throw new Error(response.data.message || '获取统计数据失败')
      }
    } catch (error) {
      console.error('获取统计数据失败:', error)
      // 返回默认数据，避免页面崩溃
      return {
        totalOrders: 0,
        productionCompletionRate: 0,
        equipmentRunningRate: 0,
        totalMaterialStock: 0,
        orderTrend: 0,
        productionTrend: 0,
        equipmentTrend: 0,
        materialTrend: 0
      }
    }
  }

  /**
   * 获取订单状态分布数据
   * @param timeRange 时间范围 (today/week/month)
   * @returns Promise<OrderStatusDistribution>
   */
  static async getOrderStatusDistribution(timeRange: string = 'today'): Promise<OrderStatusDistribution> {
    try {
      const response = await Maxios.get(`${API_BASE_URL}/GetOrderStatusDistribution`, {
        params: { timeRange }
      })
      
      if (response.data.code === 200) {
        const data = response.data.data
        return {
          timeRange: data.timeRange || timeRange,
          inProgress: data.inProgress || 0,
          completed: data.completed || 0,
          pending: data.pending || 0,
          paused: data.paused || 0
        }
      } else {
        throw new Error(response.data.message || '获取订单状态分布失败')
      }
    } catch (error) {
      console.error('获取订单状态分布失败:', error)
      // 返回默认数据
      return {
        timeRange,
        inProgress: 0,
        completed: 0,
        pending: 0,
        paused: 0
      }
    }
  }

  /**
   * 获取车间产线状态数据
   * @returns Promise<WorkshopStatus[]>
   */
  static async getWorkshopStatus(): Promise<WorkshopStatus[]> {
    try {
      const response = await Maxios.get(`${API_BASE_URL}/GetWorkshopStatus`)
      
      if (response.data.code === 200) {
        return response.data.data || []
      } else {
        throw new Error(response.data.message || '获取车间状态失败')
      }
    } catch (error) {
      console.error('获取车间状态失败:', error)
      // 返回默认数据
      return []
    }
  }

  /**
   * 获取物料库存预警数据
   * @returns Promise<MaterialAlert[]>
   */
  static async getMaterialAlerts(): Promise<MaterialAlert[]> {
    try {
      const response = await Maxios.get(`${API_BASE_URL}/GetMaterialAlerts`)
      
      if (response.data.code === 200) {
        return response.data.data || []
      } else {
        throw new Error(response.data.message || '获取物料预警失败')
      }
    } catch (error) {
      console.error('获取物料预警失败:', error)
      // 返回默认数据
      return []
    }
  }

  /**
   * 获取设备效率监控数据
   * @param timeRange 时间范围 (realtime/hour/day)
   * @returns Promise<OEEData>
   */
  static async getOEEData(timeRange: string = 'realtime'): Promise<OEEData> {
    try {
      const response = await Maxios.get(`${API_BASE_URL}/GetOEEData`, {
        params: { timeRange }
      })
      
      if (response.data.code === 200) {
        const data = response.data.data
        return {
          oee: data.oee || 0,
          availability: data.availability || 0,
          performance: data.performance || 0,
          quality: data.quality || 0
        }
      } else {
        throw new Error(response.data.message || '获取OEE数据失败')
      }
    } catch (error) {
      console.error('获取OEE数据失败:', error)
      // 返回默认数据
      return {
        oee: 0,
        availability: 0,
        performance: 0,
        quality: 0
      }
    }
  }

  /**
   * 获取实时事件数据
   * @returns Promise<RealtimeEvent[]>
   */
  static async getRealtimeEvents(): Promise<RealtimeEvent[]> {
    try {
      const response = await Maxios.get(`${API_BASE_URL}/GetRealtimeEvents`)
      
      if (response.data.code === 200) {
        return response.data.data || []
      } else {
        throw new Error(response.data.message || '获取实时事件失败')
      }
    } catch (error) {
      console.error('获取实时事件失败:', error)
      // 返回默认数据
      return []
    }
  }

  /**
   * 获取生产进度数据
   * @param viewType 视图类型 (gantt/timeline)
   * @returns Promise<ProductionProgress[]>
   */
  static async getProductionProgress(viewType: string = 'gantt'): Promise<ProductionProgress[]> {
    try {
      const response = await Maxios.get(`${API_BASE_URL}/GetProductionProgress`, {
        params: { viewType }
      })
      
      if (response.data.code === 200) {
        return response.data.data || []
      } else {
        throw new Error(response.data.message || '获取生产进度失败')
      }
    } catch (error) {
      console.error('获取生产进度失败:', error)
      // 返回默认数据
      return []
    }
  }

  /**
   * 获取完整的数据看板数据
   * @returns Promise<any>
   */
  static async getDashboardData(): Promise<any> {
    try {
      const response = await Maxios.get(`${API_BASE_URL}/GetDashboardData`)
      
      if (response.data.code === 200) {
        return response.data.data
      } else {
        throw new Error(response.data.message || '获取数据看板数据失败')
      }
    } catch (error) {
      console.error('获取数据看板数据失败:', error)
      throw error
    }
  }
}

export default DashboardService
